package tt.dz.biz.service.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import javax.annotation.Resource;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import tt.dz.biz.service.user.OperListService;
import tt.dz.common.DzDigester;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.UserErrorCode;
import tt.dz.common.RPCUtil;
import tt.dz.vo.OperListVO;

@Service("rpcModifyOperPasswordService")
public class RPCModifyOperPasswordService
  implements RPCBaseService
{
  @Resource(name="operListService")
  private OperListService operListService;
  
  public Object execute(Protocol.Message message, Object request, Protocol protocol)
    throws Exception
  {
    String name = message.getName();
    Object reqJson = ((GenericRecord)request).get("req");
    String resJson = "";
    if ("modifyOperPassword".equals(name)) {
      resJson = modifyOperPassword(reqJson.toString());
    }
    return resJson;
  }
  
  public String modifyOperPassword(String reqJson)
    throws Exception
  {
    JSONObject resObj = null;
    try
    {
      JSONObject reqObj = JSON.parseObject(reqJson);
      String managerId = reqObj.getString("managerId");
      String password = reqObj.getString("password");
      String newPassword = reqObj.getString("newPassword");
      if ((StringUtils.isBlank(managerId)) || (StringUtils.isBlank(password)) || (StringUtils.isBlank(newPassword)))
      {
        resObj = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value(), "必传参数有缺失！");
        
        return JSON.toJSONString(resObj);
      }
      OperListVO operListVO = new OperListVO();
      operListVO.setManagerId(managerId);
      operListVO.setPassword(DzDigester.sha1ForOper(password));
      List<OperListVO> operList = this.operListService.queryOperListNotLike(operListVO);
      if ((operList != null) && (operList.size() == 1))
      {
        OperListVO oper = (OperListVO)operList.get(0);
        oper.setPassword(DzDigester.sha1ForOper(newPassword));
        this.operListService.updateOperList(oper);
        resObj = RPCUtil.generateResponseObject(Integer.valueOf(1), null, null);
      }
      else
      {
        resObj = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.UserErrorCode.PASSWORD_ERROR.value(), "原始密码错误");
      }
    }
    catch (JSONException e)
    {
      resObj = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.CommonErrorCode.FORMAT_ERROR.value(), DzErrorCode.CommonErrorCode.FORMAT_ERROR
        .getDesc());
    }
    catch (Exception e)
    {
      throw e;
    }
    return JSON.toJSONString(resObj);
  }
}
